#include <ESP8266WebServer.h>
#include <ESP8266WiFi.h>

// wifi
const char* ssid     = "wifi";
const char* password = "wifipassword";
// server
ESP8266WebServer server(80);
// relay
#define OPEN_PIN 14
#define CLOSE_PIN 12
bool ISOPEN = false;


void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(OPEN_PIN, OUTPUT);
  pinMode(CLOSE_PIN, OUTPUT);
  digitalWrite(OPEN_PIN, LOW);
  digitalWrite(CLOSE_PIN, LOW);
  setWifi();
  setHttpServer();
}

void loop() {
  // put your main code here, to run repeatedly:
  server.handleClient();
}

void setWifi(){
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void setHttpServer(){
  server.on("/update", [](){
    if (server.hasArg("action")){
      if(server.arg("action") == "open" && !ISOPEN) {
        Serial.print("open");
        digitalWrite(OPEN_PIN, HIGH);
        delay(15000);
        ISOPEN = true;
        digitalWrite(OPEN_PIN, LOW);
      } else if(server.arg("action") == "close" && ISOPEN){
        Serial.print("close");
        digitalWrite(CLOSE_PIN, HIGH);
        delay(15000);
        ISOPEN = false;
        digitalWrite(CLOSE_PIN, LOW);
      }
    }
    server.send(200, "text/plain", "this works as well");
  });
  server.begin();
}
